package com.hua.gulimall.product.exception;


import com.hua.common.exception.BizCodeEnume;
import com.hua.common.utils.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

//@ResponseBody
//@ControllerAdvice(basePackages = "com.hua.gulimall.product.controller")
@RestControllerAdvice(basePackages = "com.hua.gulimall.product.controller")
public class GulimallExceptionControllerAdvice {
    private final Logger logger = LoggerFactory.getLogger(GulimallExceptionControllerAdvice.class);

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e) {
        logger.error("数据校验出现问题{}", e.getMessage(), e.getClass());
        BindingResult result = e.getBindingResult();
        Map<String, String>  map = new HashMap<>();
        result.getFieldErrors().forEach((item) -> {
            //获取错误信息如果没有自定义则是默认
            String message = item.getDefaultMessage();
            String fieid = item.getField();
            map.put(fieid, message);
        });


        return R.error(BizCodeEnume.VAILD_EXCEPTION.getCode(), BizCodeEnume.VAILD_EXCEPTION.getMsg()).put("data", map);
    }

    //用来返回其他的异常
    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable){
        logger.error("错误",throwable);
        return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(),BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
    }

}
